import importlib
import os
import pathlib
import sys
import click
from flask import Flask, request, url_for, redirect
a = Flask(__name__)
print("[INFO] Loading modules")
print("[INFO] Scanning modules")
count = 0
modobjects = {}
for i in os.listdir("mods"):
    file = pathlib.Path(os.path.join("mods", i))
    if file.is_file() and file.suffix == ".py":
        
        mod_object = importlib.import_module("mods." + file.stem)
        if not "mod" in dir(mod_object):
            click.secho("[ERROR] Module " + i.removesuffix(".py") + " don't have a mod class", fg="red")
            continue
        modobjects[i.removesuffix(".py")] = mod_object.mod()
        if not "name" in dir(mod_object.mod()):
            click.secho("[ERROR] Module " + i.removesuffix(".py") + " don't have a name", fg="red")
            modobjects.pop(i.removesuffix(".py"))
            continue
        
        print("[INFO] Loading module " + mod_object.mod().name)
        count += 1
click.secho("[INFO] find " + str(count) + " modules")
for name, obj in modobjects.items():
    if "init" in dir(obj):
        args = {}
        if "path" in obj.args:
            args["path"] = os.path.join(os.getcwd(), "mods", i.name)
        elif "userargs" in obj.args:
            args["userargs"] = sys.argv[1:]
        elif "mods" in obj.args:
            args["mods"] = modobjects
        elif "modname" in obj.args:
            args["modname"] = list(modobjects.keys())
        
        obj.init(args)
    else:
        click.secho("[ERROR] Module '" + name + "' don't have a init function", fg="red")
@a.route("/<string:module>")
def run(module):
    argslist = request.args.to_dict()
    if module in modobjects.keys():
        if not "handle" in dir(modobjects[module]):
            click.secho("[ERROR] Module '" + module + "' don't have a handle function", fg="red")
            return "Module '" + module + "' don't have a handle function", 404
        rp = modobjects[module].handle(userargs=argslist, requestobject=request)
        if rp != None:
            return str(rp)
        else:
            return "Module '" + module + "' no response", 502
    else:
        return module + " module not found"
a.run()